/**
 * Created by zhanglihe on 15/11/19.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'fineuploader',
    'datepicker'
], function ($, common, ready, Collection, template, Model, dialog, fineuploader, datepicker) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'admin_orders',
                condition: {limit: 10, offset: 0},
                model: {
                    tag_name: 'tr',
                    url: {},
                    event: {
                        '.item-follow:click': 'order_follow',
                        '.item-refund:click': 'order_refund',
                        '.item-look-new_one_order_error_type_list:click': 'new_one_order_error_type_list',
                        '.item-log:click': 'order_log'
                    },
                    order_follow: function (e) {
                        e.preventDefault();
                        var _this = this;
                        dialog({
                            title: '跟进订单:' + _this.data.sn + ',收货人:' + _this.data.shipping_name,
                            content: template('order_follow-tpl'),
                            width: 400,
                            modal: true,
                            ok: function () {
                                var data = {};
                                data.action = 'follow';
                                data.note = $('textarea[name="note"]').val();
                                if (new Model({
                                        url: _global.url.api + 'order/' + _this.data.id,
                                        data: data
                                    }).put()) {
                                }
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    new_one_order_error_type_list: function (e) {
                        e.preventDefault();
                        var _this = this;
                        dialog({
                            title: '订单:' + _this.data.sn + ',收货人:' + _this.data.shipping_name,
                            content: template('new_one_order_error_type_list-tpl', _this.data),
                            width: 800,
                            modal: true,
                            cancel: function () {
                            }
                        }).show();
                    },
                    order_refund: function (e) {
                        e.preventDefault();
                        var __this = this;
                        dialog({
                            title: '订单:' + __this.data.sn + ',收货人:' + __this.data.shipping_name,
                            content: '确定要申请退款？<br>申请后，需要商家同意操作',
                            modal: true,
                            ok: function () {
                                var data = {};
                                data.order_id = __this.data.id;
                                if (new Model({
                                        url: _global.url.api + 'order_apply_refund',
                                        data: data
                                    }).put()) {
                                    //重新加载
                                    _this.collection.reload();
                                }
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    order_log: function (e) {
                        e.preventDefault();
                        var _this = this;
                        $.ajax({
                            url: _global.url.api + 'order_log',
                            data: {id: _this.data.id},
                            type: 'get',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var dialogObj = dialog({
                                        title: '订单日志:' + _this.data.sn + ',收货人:' + _this.data.shipping_name,
                                        width: 600,
                                        height: 500,
                                        modal: true,
                                        content: template('order_log-tpl', {data: res.data}),
                                        cancel: function () {
                                            $('body').css('overflow', 'auto');
                                        }
                                    });
                                    dialogObj._$('content').css('overflow', 'auto');
                                    dialogObj.show();
                                    $('body').css('overflow', 'hidden');
                                } else {
                                    alert(res.msg);
                                }
                            }
                        });
                    }
                },
                callback: function () {
                    loaded();
                    $('.pagination').append('<li><a href="javascript:">记录总金额：￥' + _this.collection.result._amount + '</a></li>');
                }
            });
            this.collection.fetch();
        },

        event: function () {
            var _this = this;
            //日期
            $('.long_date').on('click', function () {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd HH:mm'
                });
            });
            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                click_search();
            });
            var click_search = function (fun) {
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.start_time = $('input[name="start_time"]').val();
                _this.collection.condition.end_time = $('input[name="end_time"]').val();
                _this.collection.callback = function () {
                    if (fun && fun == 'toExcel') {
                        toExcel();
                        _this.collection.callback = function () {
                        }
                    }
                }
                _this.collection.reload();
            }

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                $('input[name="keyword"]').val('');
                $('input[name="start_time"]').val('');
                $('input[name="end_time"]').val('');
                _this.collection.condition.keyword = '';
                _this.collection.condition.start_time = '';
                _this.collection.condition.end_time = '';
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            //to excel
            var href;
            var toExcelWindow;
            $(".btn-excel").on("click", function (e) {
                e.preventDefault();
                href = $(this).attr('href');
                toExcelWindow = dialog({
                    content: '请稍等 ,正在导出...',
                    width: 200,
                    modal: true
                }).show();
                click_search('toExcel');
            });
            var toExcel = function () {
                toExcelWindow.close();
                console.log(_this.collection.result._count);
                var limit = 1000;
                var params = '';
                var data = _this.collection.condition;
                var total = _this.collection.result._count;

                if (total < 1) {
                    alert('没有需要导出的订单');
                    return false;
                }

                for (var i in data) {
                    if (i == 'limit' || i == 'offset') continue;
                    params = params + '&' + i + '=' + encodeURIComponent(data[i]);
                }
                href = (href.indexOf('?') === -1) ? href + '?' : href;
                href = href + params + '&limit=' + limit + '&offset=';

                if (total > limit) {
                    var showData = {};
                    showData.pages = Math.ceil(total / limit);
                    showData.total = total;
                    showData.limit = limit;
                    showData.href = href;
                    dialog({
                        title: '导出订单列表Excel文件',
                        content: template('to-excel-tpl', showData),
                        width: 600,
                        heigth: 500,
                        modal: true,
                        ok: function () {
                        },
                        cancel: function () {
                        }
                    }).show();
                } else {
                    window.location.href = href;
                }
            }

        }
    };

    new index();

});